Ext.define('Projeto.controller.User', {
    extend: 'Ext.app.Controller',
    
    stores: ['Users', 'Niveis'],
    
    refs: [{
    	ref: 'cboNivel',
    	selector: 'useredit > form > combobox[id=cboNivel]'
    }],
    
    init: function() {
        this.control({
        	'userlist' : {
        		render: this.onListRender,
        		itemdblclick: this.onItemClick
        	},
        	
            'userlist > toolbar > button[action=new]' : {
                click: this.newUser
            },
            
            'useredit > form > toolbar > button[action=save]': {
            	click: this.onSaveUser
            }
    
        });
    },

    newUser: function() {
        var view = Ext.widget('useredit');
    },
    
    onItemClick: function(view, record, item, index, event, opts) {
    	var view = Ext.widget('useredit');
    	var form = view.down('form');
    	form.loadRecord(record);
    	this.getCboNivel().select(record.get('nivelId'));
    },
    
    onListRender: function() {
    	this.getUsersStore().load();
    	this.getNiveisStore().load();
    },
    
    onSaveUser: function(button) {
    	var form = button.up('form');
    	var record = form.getRecord();
    	var values = form.getValues();
    	
    	if (!record) {
    		var user = Ext.create('Projeto.model.User');
    		user.set(values);
    		this.getUsersStore().add(user);
    	} else {
    		record.set(values);
    	}
    	
    	this.getUsersStore().sync();
    	this.getUsersStore().load();
    	form.up('window').close();
    }
});